import classnames from 'classnames'
import { useHistory } from 'react-router'
import { Dialog, NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import { getclearhistory, getsearch, getsearchhisotry } from '@/store/actions/search'
import { RootState } from '@/types/store'
import { highLight } from '@/utils/highLight'
import { removehistory } from '@/utils/storagehistory'
const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // const timeRef=useRef(0)
  const [keyword, setkeyword] = useState('')
  const { run: getSuggest } = useDebounceFn(async (e: string) => {
    console.log(e);
    await dispatch(getsearch(e))
  }, { wait: 500 })
  const changeSearch = (e: string) => {
    // window.clearInterval(timeRef.current)
    // timeRef.current=window.setTimeout(()=>{
    //     console.log(e);
    // },500)
    setkeyword(e)
    if (e) {
      getSuggest(e)
    }

  }
  const { suggestion, searchHistory } = useSelector((state: RootState) => state.search)
  const onsearch = async(keyword: string) => {
    //  查找如果找到相同的历史记录 则删除一个
    const historyindex = searchHistory.findIndex(item => item===keyword)
    if(historyindex!==-1){
      searchHistory.splice(historyindex,1)
    }
    // console.log([...searchHistory]);
    const newkeyword=[keyword,...searchHistory]
    // sethistory(newkeyword)
   await dispatch(getsearchhisotry(newkeyword))
   history.push('/search/result?keyword='+keyword)
  }
  const onclearlist = ()=>{ //清除历史记录
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要清空记录吗？',
      onConfirm: function () {
        dispatch(getclearhistory())
        removehistory()
      },
    })
  }
  const onclear=async(it:string)=>{ //清除单个
    //  查找如果找到相同的历史记录 则删除一个
    const historyindex = searchHistory.findIndex(item => item===it)
    if(historyindex!==-1){
      searchHistory.splice(historyindex,1)
    }
   await dispatch(getsearchhisotry(searchHistory))
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={<span className="search-text" onClick={() => onsearch(keyword)}>搜索</span>}
      >
        <SearchBar value={keyword} onChange={changeSearch} placeholder="请输入关键字搜索" />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: keyword.length ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span
            onClick={onclearlist}
            >
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {searchHistory.map((item, idx) => {
              return (
                <span key={idx} className="history-item">
                  <span className="text-overflow" onClick={() => onsearch(item)}>{item}</span>
                  <Icon type="iconbtn_essay_close" onClick={()=>onclear(item)} />
                </span>
              )
            })}
          </div>
        </div>
      )}

      <div className={classnames('search-result', { 'show': keyword.length })}>
        {
          suggestion.map((item, idx) => (
            <div className="result-item" key={idx}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value text-overflow"
                onClick={() => onsearch(item)}
                dangerouslySetInnerHTML={{
                  __html: highLight(String(item), keyword)
                }}
              ></div>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default SearchPage